package com.liankuan.console.config;

import com.github.pagehelper.util.StringUtil;
import com.liankuan.console.annotation.IgnoreSecurity;
import com.liankuan.console.common.ResultEnum;
import com.liankuan.console.dto.User;
import com.liankuan.console.exception.ServiceException;
import com.liankuan.console.service.UserService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author bobo
 */
@Slf4j
@Component
@NoArgsConstructor
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//        request.getHeader("Access-Control-Allow-Origin: *");
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();


        if (method.isAnnotationPresent(IgnoreSecurity.class)) {
            return true;
        }
        String token = request.getHeader("X-Token");

        if (StringUtil.isEmpty(token)) {
            throw new ServiceException(ResultEnum.NOT_INVALID_TOKEN);
        }
        User user = userService.getUserInfoByToken(token);

        //用户已经在其他地方登陆
        if (user == null) {
            throw new ServiceException(ResultEnum.NOT_TOKEN);
        }

        request.setAttribute("userId", user.getId());
        return true;
    }
}